package com.ilarele.shopping.client.adaptors;

import java.util.ArrayList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;

import com.ilarele.shopping.Product;
import com.ilarele.shopping.ProductLocation;
import com.ilarele.shopping.client.R;
import com.ilarele.shopping.client.util.DrawableManager;
import com.ilarele.shopping.client.util.Global;

public class A1ProductAdapter extends ArrayAdapter<Product> {
	private final LayoutInflater mLayoutInflater;

	/**
	 * Contains the list of objects that represent the data of this
	 * ArrayAdapter. The content of this list is referred to as "the array" in
	 * the documentation.
	 */
	private ArrayList<Product> mObjects;
	private ArrayList<Product> mOriginalValues;

	/**
	 * Lock used to modify the content of {@link #mObjects}. Any write operation
	 * performed on the array should be synchronized on this lock. This lock is
	 * also used by the filter (see {@link #getFilter()} to make a synchronized
	 * copy of the original array of data.
	 */
	private final Object mLock = new Object();
	private ShoppingFilter mFilter;

	private Sorter sorter;

	public A1ProductAdapter(Activity activity, ArrayList<Product> items) {
		super(activity, R.layout.a1_shoppinglist_item, items);

		float latitude = Global.pref.getFloat("latitude", 0);
		float longitude = Global.pref.getFloat("latitude", 0);
		ProductLocation pLocation = new ProductLocation("none", latitude,
				longitude);
		sorter = new Sorter(pLocation);

		mObjects = items;
		mLayoutInflater = LayoutInflater.from(activity);
		mFilter = new ShoppingFilter();
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {
		ViewHolder holder;

		if (view == null) {
			view = mLayoutInflater.inflate(R.layout.a1_shoppinglist_item,
					parent, false);

			holder = new ViewHolder();
			holder.name = (TextView) view.findViewById(R.id.list_item_name);
			holder.picture = (ImageView) view
					.findViewById(R.id.list_item_picture);

			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}
		// final CrossFadeDrawable transition = new CrossFadeDrawable(
		// mDefaultPictureBitmap, null);
		// transition.setCallback(view);
		// transition.setCrossFadeEnabled(true);

		Product item = getItem(position);
		holder.name.setText(item.pName.name);
		holder.id = item.idProd;
		// holder.internalId = item.internalId;

		if (item.pPicture.imageUrl != null
				&& !item.pPicture.imageUrl.equals("null"))
			DrawableManager.fetchView(item.pPicture.imageUrl, holder.picture);
		else
			holder.picture.setImageResource(R.drawable.icon);

		return view;
	}

	public void refreshFilter(String word) {
		mFilter.filter(word);
	}

	@Override
	public Filter getFilter() {
		return mFilter;
	};

	/**
	 * Sorts the content of this adapter using the specified comparator.
	 * 
	 * @param comparator
	 *            The comparator used to sort the objects contained in this
	 *            adapter.
	 */

	private static class ViewHolder {
		// public String internalId;
		// public boolean queryPicture;
		@SuppressWarnings("unused")
		String id;
		TextView name;
		ImageView picture;
	}

	private class ShoppingFilter extends Filter {
		@Override
		protected FilterResults performFiltering(CharSequence prefix) {
			// NOTE: this function is *always* called from a background thread,
			// and
			// not the UI thread.
			FilterResults results = new FilterResults();
			synchronized (mLock) {
				if (mOriginalValues == null) {
					mOriginalValues = new ArrayList<Product>(mObjects);
				}
			}

			if (prefix == null || prefix.length() == 0) {
				synchronized (mLock) {
					ArrayList<Product> list = new ArrayList<Product>(
							mOriginalValues);
					results.values = list;
					results.count = list.size();
				}
			} else {
				ArrayList<Product> newValues = new ArrayList<Product>();
				synchronized (mLock) {
					for (Product product : mOriginalValues) {
						if ((product.pName.name != null && product.pName.name
								.toLowerCase().contains(
										prefix.toString().toLowerCase()))
								|| (product.pTags.tags != null)
								&& product.pTags.tags.toLowerCase().contains(
										prefix.toString().toLowerCase())) {
							newValues.add(product);
						}
					}
				}
				results.values = newValues;
				results.count = newValues.size();
			}
			return results;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected void publishResults(CharSequence constraint,
				FilterResults results) {
			// NOTE: this function is *always* called from the UI thread.
			if (results.values != null) {
				mObjects.clear();
				mObjects.addAll((ArrayList<Product>) results.values);
				if (results.count > 0) {
					notifyDataSetChanged();
				} else {
					notifyDataSetInvalidated();
				}
			}
		}
	}

	public void setSortCriteria(int criteria) {
		sorter.setSortCriteria(criteria);
		sort(sorter.getCurrentComparator());
	}

	public void addFirst(Product prod) {
		insert(prod, 0);
	}

	@Override
	public int getPosition(Product item) {
		return mObjects.indexOf(item);
	}

	public void setSortDirection(int dir) {
		sorter.setSortDirection(dir);
		sort(sorter.getCurrentComparator());
	}
}
